import { regExpValidateHandler } from '@/utils/formValidators'

import { useConfigStore } from '@/stores/config'
import type {
  IMatchConfig,
  MultipleOperatorType,
  OperatorOption
} from './types'

/**
 * 根据不同字段动态生成运算符
 * @param type
 * @returns
 */
export function generateOperatorOptions(types: MultipleOperatorType[]) {
  const operations: OperatorOption[] = [
    { label: '等于', value: 'eq', template: '$field eq $value' },
    { label: '不等于', value: 'ne', template: '$field ne $value' }
  ]
  if (types.includes('contains')) {
    operations.push(
      {
        label: '包含',
        value: 'contains',
        template: `$field contains $value`
      },
      {
        label: '不包含',
        value: 'not_contains',
        template: `not $field contains $value`
      }
    )
  }
  if (types.includes('in')) {
    operations.push(
      { label: '包含以下各项', value: 'in', template: `$field in $value` },
      {
        label: '不包含以下各项',
        value: 'not_in',
        template: `not $field in $value`
      }
    )
  }
  return operations
}
// const fieldEnum = {
//   uri: {
//     placeholder: ' https://example.com/contact?page=1234'
//   },
//   path: {
//     placeholder: '/contact'
//   },
//   ip: {
//     placeholder: ' 192.0.2.0',
//     validator: validateIpv4
//   },
//   referer: {
//     placeholder: ' example.com',
//     validator: (value, callback) => {
//       const validators = [regexpMap.domain, regexpMap.ipv4]
//       const errFlag = validators.every((regexp) =>
//         regExpValidateHandler(value as string, regexp, 'error')
//       )
//       errFlag ? callback('Referer格式错误') : callback()
//     }
//   },
//   user_agent: {
//     placeholder: ' Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)',
//     validator(value, callback) {
//       if (!value) {
//         return
//       }
//       if (value.toString().length > 255) {
//         callback('长度最大255个字符')
//         return
//       }
//       callback()
//     }
//   },
//   cookie: {
//     placeholder: 'name=value'
//   },
//   host: {
//     placeholder: 'example.com',
//     validator: validateDomain
//   },
//   method: {
//     placeholder: ' GET'
//   },
//   query_string: {
//     placeholder: 'name=value'
//   },
//   http_version: {
//     placeholder: 'HTTP/1.0'
//   },
//   x_forwarded_for: {
//     placeholder: ' 192.0.2.0, 192.0.4.0',
//     validator(value, callback) {
//       const arr = (value as string).split(',')
//       callback(
//         validateHandler(arr, (data) => {
//           return regExpValidateHandler(data, regexpMap.ipv4, 'IP地址格式错误')
//         })
//       )
//     }
//   },
//   content_type: {
//     placeholder: 'text/html'
//   },
//   content_length: {
//     placeholder: '12345'
//   },
//   header: {
//     placeholder: 'name=value'
//   },
//   file_ext: {
//     placeholder: '.html'
//   },
//   filename: {
//     placeholder: 'index.html'
//   },
//   query_string_param: {
//     placeholder: 'name=value'
//   },
//   cookie_name: {
//     placeholder: 'name'
//   },
//   server_port: {
//     placeholder: '80'
//   },
//   continent: {
//     placeholder: '南极洲'
//   },
//   country: {
//     placeholder: '中国'
//   }
// }

export function getMatchConfig() {
  const conditionQuery = useConfigStore().conditionQuery
  const config = [] as IMatchConfig[]
  for (const cg of conditionQuery) {
    const valueOptions = cg.operators.find((item: any) => {
      return item.field === 'times' && item.allowed_values?.length
    })
    const obj = {
      operatorOptions: cg.operators.map((item: any) => ({
        value: item.field,
        label: item.show_name,
        allowed_values: item.allowed_values || [],
        ...item.value
      })),
      label: cg.field.show_name,
      value: cg.field.field,
      needCustomField: cg.field.need_custom_field,
      customFieldExample: cg.field.custom_field_example,
      valueOptions: valueOptions?.allowed_values || [],
      field: {
        type: cg.allowed_values?.length ? 'select' : 'input',
        placeholder: '',
        // (cg.allowed_values.length ? `请选择值，示例：` : `请输入值，示例：`) +
        // `${fieldEnum[cg.field.field].placeholder}`,
        options: cg.allowed_values?.length ? cg.allowed_values : []
        // validator: [fieldEnum[cg.field.field].validator]
      }
    }
    config.push(obj)
  }
  return config
}
export const matchConfig: IMatchConfig[] = [
  {
    label: 'Cookie',
    value: 'http.cookie',
    operatorOptions: generateOperatorOptions(['contains']),
    field: {
      type: 'input',
      placeholder: '请输入值，示例：name=value'
    }
  },
  {
    label: '国家/地区',
    value: 'ip.geoip.country',
    operatorOptions: generateOperatorOptions(['in']),
    field: {
      type: 'select',
      placeholder: '请选择值，示例：中国',
      options: () => {
        const configStore = useConfigStore()
        return configStore.config.countryList
      }
    }
  },
  {
    label: '洲',
    value: 'ip.geoip.continent',
    operatorOptions: generateOperatorOptions(['in']),
    field: {
      type: 'select',
      placeholder: '请选择值，示例：南极洲',
      options: () => {
        const configStore = useConfigStore()
        return configStore.config.continentList
      }
    }
  },
  {
    label: '主机名（域名）',
    value: 'http.host',
    operatorOptions: generateOperatorOptions(['in', 'contains']),
    field: {
      type: 'input',
      placeholder: '请输入值，示例：example.com',
      validator: validateDomain
    }
  },
  {
    label: '源 IP 地址',
    value: 'ip.src',
    operatorOptions: generateOperatorOptions(['in']),
    field: {
      type: 'input',
      placeholder: '请输入值，示例: 192.0.2.0',
      validator: validateIpv4
    }
  },
  {
    label: 'Referer',
    value: 'http.referer',
    operatorOptions: generateOperatorOptions(['in', 'contains']),
    field: {
      type: 'input',
      placeholder: '请输入值，示例: example.com',
      validator: (value, callback) => {
        const validators = [regexpMap.domain, regexpMap.ipv4]
        const errFlag = validators.every((regexp) =>
          regExpValidateHandler(value as string, regexp, 'error')
        )
        errFlag ? callback('Referer格式错误') : callback()
      }
    }
  },
  {
    label: '请求方法',
    value: 'http.request.method',
    operatorOptions: generateOperatorOptions(['in']),
    field: {
      type: 'select',
      placeholder: '请输入值，示例: GET',
      options: () => {
        const configStore = useConfigStore()
        return configStore.config.supportMethod
      }
    }
  },
  {
    label: 'SSL/HTTPS',
    value: 'ssl',
    operatorOptions: generateOperatorOptions(['in']),
    field: { type: 'switch', valueType: 'boolean' }
  },
  {
    label: 'URL 地址',
    value: 'http.request.full_uri',
    operatorOptions: generateOperatorOptions(['in', 'contains']),
    field: {
      type: 'input',
      placeholder: '请输入值，示例: https://example.com/contact?page=1234',
      validator: validateURL
    }
  },
  {
    label: 'URL 路径',
    value: 'http.request.uri.path',
    operatorOptions: generateOperatorOptions(['in', 'contains']),
    field: {
      type: 'input',
      placeholder: '请输入值，示例：/contact',
      validator: validateUrlPath
    }
  },
  {
    label: 'URL 参数',
    value: 'http.request.uri.query',
    operatorOptions: generateOperatorOptions(['in', 'contains']),
    field: {
      type: 'input',
      placeholder: '请输入值，示例：page=1234'
    }
  },
  {
    label: 'HTTP 版本',
    value: 'http.request.version',
    operatorOptions: generateOperatorOptions(['in']),
    field: {
      type: 'select',
      placeholder: '请输入值，示例: HTTP/2.0',
      options: () => {
        const configStore = useConfigStore()
        return configStore.config.supportHttpVersion
      }
    }
  },
  {
    label: 'User-Agent',
    value: 'http.user_agent',
    operatorOptions: generateOperatorOptions(['in', 'contains']),
    field: {
      type: 'input',
      placeholder:
        '请输入值，示例: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)',
      validator(value, callback) {
        if (!value) {
          return
        }
        if (value.toString().length > 255) {
          callback('长度最大255个字符')
          return
        }
        callback()
      }
    }
  },
  {
    label: 'X-Forwarded-For',
    value: 'http.x_forwarded_for',
    operatorOptions: generateOperatorOptions(['contains']),
    field: {
      type: 'input',
      valueType: 'array',
      placeholder: '请输入值，示例: 192.0.2.0, 192.0.4.0',
      validator(value, callback) {
        const arr = (value as string).split(',')
        callback(
          validateHandler(arr, (data) => {
            return regExpValidateHandler(
              data,
              regexpMap.ipv4,
              'IP 地址格式错误'
            )
          })
        )
      }
    }
  }
]
/**
 * 获取字段配置
 * @param field
 * @returns
 */
export function getFieldConfig(field: string, configs?: IMatchConfig[]) {
  if (!configs) {
    configs = matchConfig
  }
  return configs.find((config) => config.value === field)
}
